
#helper functions
module ShibbolethHelper

  def shibboleth_enabled?
    Shibboleth::enabled
  end
  
  #uri escape including forward slashes (/)
  def url_escape param
    URI.escape(param, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))
  end
  
  #return a shibboleth login url for a specific idp
  #if idp is blank returns a login url to the default login service - i.e. wayf
  def shibboleth_login_url idp=''
    host = request.host
    if idp.blank?
      return ""
    end

    sso = "https://#{host}/Shibboleth.sso/DS"
    target = "https://#{host}/shibboleth/login"
    target = url_escape(target)  #request.urls
    
    entity_id = url_escape(idp)
    result = "#{sso}?entityID=#{entity_id}&amp;target=#{target}"
  end  

  #render the shibboleth login screen
  def shibboleth_login_title
    unless Shibboleth::enabled
      return ''
    end
    t('aai.login_title')
  end

  #render the shibboleth login screen
  def shibboleth_login_tag
    unless Shibboleth::enabled
      return false
    end
    login = Shibboleth::settings['login']
    login = login.blank? ? 'default' : login
    render "shibboleth/login_#{login}"
  end
  
  #render a select box with the list of shibboleth login screens availables
  def select_logins_tag(name, value)
    options = ''
    dir = Dir[Shibboleth.root('app', 'views', 'shibboleth', '_login*')]
    
    dir.each do |file|  
      option_value = file.split('/').last
      option_value = option_value.gsub(/_login_/,  '').gsub(/[.]html[.]erb/, '')
      if value == option_value
        options += "<option selected value=\"#{option_value}\">#{option_value}</option>"
      else
        options += "<option value=\"#{option_value}\">#{option_value}</option>"
      end
    end
    select_tag name, options
  end
  
  #returns link tags to the shibboleth css(s)
  def shibboleth_stylesheets_tag
    unless Shibboleth::enabled
      return false
    end
    result = ''
    dir = Dir[Shibboleth.root('public', 'stylesheets', '*')]
    dir.each do |file|     
      file_name = file.split('/').last
      ENV
      result += stylesheet_tag "/shibboleth/stylesheets/#{file_name}?#{timestamp}", {}     
    end    
    result
  end
  
  private
  
  @@_timestamp = nil
  
  #timestamp for static ressources. Used to enabled browser caching.
  def timestamp
    if @@_timestamp != nil
      return @@_timestamp
    end
    if result = ENV['RAILS_ASSET_ID']
      return @@_timestamp = result
    end
    path = Shibboleth.root('public', 'stylesheets', 'shibboleth.css')
    @@_timestamp = File.exist?(path) ? File.mtime(path).to_i.to_s : ''
  end
    
end
